<?php

namespace app\admin\controller\sales;

use app\common\model\factory\Goods as fGoods;
use app\common\model\factory\Sales;
use app\common\model\goods\Goods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\sales\Goods as sGoods;
use app\common\model\sales\CheckoutGoods;
use app\common\controller\Backend;
use app\common\model\customer\Customer;
use app\common\model\sales\SalesSlip;
use app\common\model\Storehouse;
use app\common\model\supplier\Supplier;
use app\web\controller\Wweixin;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Slip extends Backend
{
    
    /**
     * Slip模型对象
     * @var \app\common\model\sales\Slip
     */
    protected $model = null;
//    protected $searchFields = 'customer.company,number,slip.number';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\sales\Slip;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);
            $where=[];
            if(session('admin')['storehouse_id'] >0){
                $where['ss.storehouse_id'] = session('admin')['storehouse_id'];
            }
            $search = trim(input('search'));
            if(!empty($search)){
                $where1['company'] = array('like','%'.trim($search).'%');
                $list =  Customer::where($where1)->field('id')->select();
                if(!empty($list)){
                    foreach ($list as $v){
                        $ids[] = $v['id'];
                    }
                    $where['ss.customer_id'] = array('in',$ids);
                }
            }

            if(!empty($filter)){
                foreach ($filter as $key =>$value){
                    if($key == 'goods_name'){
                        $gids = Db::name('goods')->where(array('title'=>array('like','%'.trim($value).'%')))->column('id');
                        $sids = Db::name('sales_goods')->where(array('goods_id'=>array('in',$gids)))->column('sales_slip_id');
                        $where['ss.id'] = array('in',$sids);
                    }
                    if($key == 'goods_number'){
                        $gids = Db::name('goods')->where(array('number'=>$value))->find();
                        $sids = Db::name('sales_goods')->where(array('goods_id'=>$gids['id']))->column('sales_slip_id');
                        $where['ss.id'] = array('in',$sids);
                    }
                    if($key == 'number'){
                        $where['ss.number'] = array('like','%'.trim($value).'%');
                    }
                    if($key == 'operator'){
                        $where['ss.operator'] = array('like','%'.trim($value).'%');
                    }
                    if($key == 'company'){
                        $where['ss.company'] = array('like','%'.trim($value).'%');
                    }
                    if($key == 'id'){
                        $where['ss.id'] = $value;
                    }
                    if($key == 'status'){
                        if($value == 7){
                            $where['ss.status'] = $value;
                            $where['ss.admin_id'] = session('admin')['id'];
                        }else{
                            $where['ss.status'] = $value;
                        }
                    }
                    if($key == 'name'){//仓库
                        $where2['name'] = $value;
                        $info = Storehouse::where($where2)->find();
                        $where['ss.storehouse_id'] = $info['id'];
                    }
                    if($key == 'ccompany'){
                        $where1['company'] = array('like','%'.trim($value).'%');
//                        exit;
                        $list =  Customer::where($where1)->field('id')->select();

                        if(!empty($list)){
                            foreach ($list as $v){
                                $ids[] = $v['id'];
                            }
                            $where['ss.customer_id'] = array('in',$ids);
                        }
                    }
                    if($key == 'createtime'){
                        $arr = explode(' - ', $value);
                        $where['ss.createtime'] = array('between time',$arr);
                    }
                    if($key == 'deliverytime'){
                        $arr = explode(' - ', $value);
                        $where['ss.deliverytime'] = array('between time',$arr);
                    }
                }
            }
            if(!isset($where['ss.status'])){
                $where['ss.status'] = array('neq',7);
            }
            $offset = input('offset');
            $limit = input('limit');
            $list = Db::name('sales_slip')
                ->field('ss.id,ss.number,ss.createtime,ss.deliverytime,ss.explain,ss.abstract,ss.operator,ss.company,ss.tax,c.company as ccompany,h.name,ss.status,sales_num,actual_cost,ss.admin_id')
                ->alias('ss')
                ->where($where)
                ->join('zax_customer c','ss.customer_id = c.id')
                ->join('zax_storehouse h','ss.storehouse_id = h.id')
                ->limit($offset,$limit)
                ->order('ss.id','DESC')
                ->select();
            $total= Db::name('sales_slip')
                ->alias('ss')
                ->where($where)
                ->join('customer c','ss.customer_id = c.id')
                ->join('storehouse h','ss.storehouse_id = h.id')
                ->count();
//            $num = Db::name('sales_slip')
//                ->alias('ss')
//                ->where($where)
//                ->join('customer c','ss.customer_id = c.id')
//                ->join('storehouse h','ss.storehouse_id = h.id')
//                ->sum('sales_num');
//            $price = Db::name('sales_slip')
//                ->alias('ss')
//                ->where($where)
//                ->join('customer c','ss.customer_id = c.id')
//                ->join('storehouse h','ss.storehouse_id = h.id')
//                ->sum('actual_cost');
            $status = $this->model->slip_status();
            $group = Db::name('auth_group_access')->where(array('uid' => session('admin')['id']))->find();

            foreach ($list as $k => $v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $status[$v['status']];
                if(session('admin')['id'] == 1 || session('admin')['id'] == $v['admin_id'] || $group['group_id'] == 1){
                    $list[$k]['is_edit'] = 1;
                }else{
                    $list[$k]['is_edit'] = 0;
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->assign('statusList',[
//            7=>'草稿'
        ]);
        return $this->view->fetch();
    }


    public function getcount()
    {


//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = input('');
            $where=[];
            $where['ss.status'] = array('in',[1,2,3,4,5,8]);
            if(session('admin')['storehouse_id'] >0){
                $where['ss.storehouse_id'] = session('admin')['storehouse_id'];
            }


            if(!empty($filter)){
                foreach ($filter as $key =>$value){
                    if($key == 'number' && !empty($value)){
                        $where['ss.number'] = array('like','%'.$value.'%');
                    }
                    if($key == 'operator' && !empty($value)){
                        $where['ss.operator'] = array('like','%'.$value.'%');
                    }
                    if($key == 'company' && !empty($value)){
                        $where['ss.company'] = array('like','%'.$value.'%');
                    }
                    if($key == 'id' && !empty($value)){
                        $where['ss.id'] = $value;
                    }
                    if($key == 'status' && !empty($value)){
                        $where['ss.status'] = $value;
                    }
                    if($key == 'name' && !empty($value)){//仓库
                        $where2['name'] = $value;
                        $info = Storehouse::where($where2)->find();
                        $where['ss.storehouse_id'] = $info['id'];
                    }
                    if($key == 'ccompany' && !empty($value) && !empty($value)){
                        $where1['company'] = array('like','%'.$value.'%');
                        $list =  Customer::where($where1)->field('id')->select();

                        if(!empty($list)){
                            foreach ($list as $v){
                                $ids[] = $v['id'];
                            }
                            $where['ss.customer_id'] = array('in',$ids);
                        }
                    }
                    if($key == 'createtime' && !empty($value)){
                        $arr = explode(' - ', $value);
                        $where['ss.createtime'] = array('between time',$arr);
                    }
                    if($key == 'deliverytime' && !empty($value)){
                        $arr = explode(' - ', $value);
                        $where['ss.deliverytime'] = array('between time',$arr);
                    }
                }
            }

            $num = Db::name('sales_slip')
                ->alias('ss')
                ->where($where)
                ->join('customer c','ss.customer_id = c.id')
                ->join('storehouse h','ss.storehouse_id = h.id')
                ->sum('sales_num');
            $price = Db::name('sales_slip')
                ->alias('ss')
                ->where($where)
                ->join('customer c','ss.customer_id = c.id')
                ->join('storehouse h','ss.storehouse_id = h.id')
                ->sum('actual_cost');

            $result = array('num'=>$num,'price'=>$price);

            return json($result);
    }

    public function add()
    {
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        if ($this->request->isAjax()) {

            $customer_id = input('customer_id/d',0);

            $storehouse_id = input('storehouse_id/d',0);

            $hrow = Db::name('storehouse')->where(array('id'=>$storehouse_id))->find();

            $deliverytime = strtotime(input('deliverytime'));
//            $createtime = strtotime(input('createtime'));
            $tax = floatval(input('tax'));
            if(!is_float($tax) || $tax >13){
                $this->error('请检查税费');
            }
            $draft = input('draft');



            $explain = input('explain');
            $abstract = input('abstract');
            $mobile = input('mobile');
            $address = input('address');
            $contacts = input('contacts');
            $sales_type_id = input('sales_type_id');
            $sales_number = input('sales_number');

            $allfare = input('allfare/d');
            $discount = input('discount');
            $discount_explain = input('discount_explain');
            $actual_cost = input('actual_cost');
            if(empty($actual_cost)){
                $this->error('费用计算错误');
            }
            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            $sale_num = 0;

            $sdata = $params['row'];

            $gids = [];
            $numbers = [];
            $allprice = 0;
            foreach ($sdata as $k=> $v){
                $sdata[$k]['tax'] = floatval(input('tax'));
                if(!is_float($sdata[$k]['tax'])){
                    $this->error('商品'.$v['goods_id'].'税费设置有误');
                }
                $sale_num +=$v['goods_num'];
                $gids[] = $v['goods_id'];
                $allprice+=$v['sfhj'];
                if(empty($v['sfhj']) || $v['sfhj'] == 0.00){
                    if( $v['sale_price'] >0){
                        $this->error('费用异常');
                    }
                }
            }
//            dump($allprice);
//            dump($allfare);
//            dump($actual_cost);
//            if(($allprice+$allfare) - $actual_cost !=0){
            if(!compare($allprice+$allfare,$actual_cost)){
                $this->error('计算费用错误');
            }

//            exit;
            $gids = array_unique($gids);
            if(count($gids) != count($sdata)){
                $this->error('商品存在重复');
            }

            $crow = Customer::get($customer_id);
            if(empty($crow)){
                $this->error('客户异常');
            }
            if(empty($explain)){
                $explain = $crow['replenish'];
            }else{
                $explain .= '，'.$crow['replenish'];
            }

            $slipnum = Db::name('sales_slip')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->order('id','desc')->find();
            if($slipnum){
                $num=intval(substr($slipnum['number'],-4));
            }else{
                $num = 0;
            }

            $saledata = array(
              'number'=>'XD-'.date('Ymd').'-'.getnumber($num),
                'sales_type_id'=>$sales_type_id,
                'sales_number'=>$sales_number,
                'allfare'=>$allfare,
//                'discount'=>$discount,
//                'discount_explain'=>$discount_explain,
                'actual_cost'=>$actual_cost,
                'deliverytime'=>$deliverytime,
                'customer_id'=>$customer_id,
                'storehouse_id'=>$storehouse_id,
                'explain'=>$explain,
//                'abstract'=>$abstract,
                'address'=>$address,
                'mobile'=>$mobile,
                'contacts'=>$contacts,
                'tax'=>$tax,
                'sales_num'=>$sale_num,
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
            );
//            if($draft){
//                $saledata['status'] = 7;
//            }else{
//                $this->error('已禁止,没有添加销售记录');
//                exit;
                $goodss = Db::name('goods')->where(array('id'=>array('in',$gids)))->select();
                foreach ($goodss  as $k => $v){
                    foreach ($sdata as $key=> $val){
                        if($v['id'] == $val['goods_id']){
                            $goodss[$k]['sale_price']=$sdata[$key]['sale_price'];
                        }
                    }
                    $numbers[] = $v['number'];
                }
                $hrow = Db::name('storehouse')->where(array('id'=>$storehouse_id))->find();
                $prices = $this->getprice(implode(',',$numbers),$hrow['code']);

                foreach ($prices as $v){
                    foreach ($goodss as &$val){
                        if($val['number'] == $v['spec_num']){
                            $val['jxs_price'] = $v['jxs_price'];
                        }
                    }
                }
                $slipstatus = 2;

                foreach ($goodss as $v){
                    if(isset($v['jxs_price'])){ //
                        if($v['jxs_price'] > $v['sale_price']){
                            $slipstatus = 1;
                        }
                    }else{
                        $house = new Goods();
                        $price = $house->getcost($v['id'],$storehouse_id);
                        if($price > $v['sale_price']){
                            $slipstatus = 1;
                        }
                    }
                }
                $saledata['status'] = $slipstatus;
//            }

            if($hrow['sale_status'] == 1){
                $saledata['status'] = 2;
            }


            Db::startTrans();
            try {
                $this->model->save($saledata);
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$storehouse_id,
                    'bill_id'=>$this->model->id,
                    'type'=>6,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                if(!$this->model->id){
                    throw new Exception('添加失败');
                }

                $gdata = [];

                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'storehouse_id' => $storehouse_id,
                        'customer_id' => $customer_id,
                        'sales_slip_id' => $this->model->id,
                        'createtime'=>time(),
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'sfhj'=>$v['sfhj'],
                        'operator'=>session('admin')['nickname'],
                    );
                    Db::name('goods')->where(array('id'=>$v['goods_id']))->setInc('weigh');
                }
                $sGoods = new sGoods;
                $sGoods->saveAll($gdata);

                if(isset($saledata['status']) && $saledata['status'] ==7){

                }else{
                    $wx = new Wweixin;
                    $wx->senmsg(6);
                }

                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'创建成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $types =  Db::name('sales_type')->where(array('status'=>1))->select();
        $this->assign('types',$types);

//        $arr = explode('/',$_SERVER['REQUEST_URI']);
//        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }

    protected function getprice($numbers,$code){
        $url =  config('site.syncurl').'/api/sync/batchprice';
        $json = curl_post($url,array(
            'numbers'=>$numbers,
            'code'=>$code,
            'appkey'=>config('site.appkey'),
        ));
        $json = json_decode($json,true);
        if(isset($json['code']) && $json['code'] == 9){
            return [];
        }
        if(!empty($json) && $json['code']  == 1){
            return $json['data'];
        }else{
            return [];
        }
    }
    public function seach(){
        $house_id = input('house_id/d',0);

        $this->assign('house_id',$house_id);
        return $this->view->fetch();
    }
    public function getgood($ids = null){
        $house_id = input('house_id/d',0);
        $hrow = Db::name('storehouse')->where(array('id'=>$house_id))->find();
        $good = new Goods();
        $ginfo = $good->where(array('id'=>$ids))->find();
        if(empty($ginfo)){
            $this->error('无商品');
        }
        // $url =  config('site.syncurl').'/api/sync/getprice';
        // $json = curl_post($url,array(
        //     'spec_num'=>$ginfo['number'],
        //     'code'=>$hrow['code'],
        //     'appkey'=>config('site.appkey'),
        // ));
        // $json = json_decode($json,true);
        // if(isset($json['code']) && $json['code'] == 9){
        //     return $json;
        // }
        if(!empty($json) && $json['code']  == 1){
            $ginfo['price'] = $json['data'];
        }else{
            $ginfo['price'] = 0;
        }
        $GoodsHouseStock = new GoodsHouseStock;
        $ginfo['xstock'] = $GoodsHouseStock->getfictstock($ginfo['id'],$house_id);
        $ginfo['stock'] = $GoodsHouseStock->getstock($ginfo['id'],$house_id);
        return $ginfo;
    }
    public function detail($ids = null){

        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        if ($this->request->isAjax()) {
            $status = input('status/d',0);
            if(!$status){
                $this->error('非法操作');
            }
            Db::startTrans();
            try {
                $res = $this->model->save(array('status' => $status), array('id' => $ids));
                if ($res) {
                    $type = 1;
                    if($status == 6){ //审核拒绝
                        $type = 2;
                        $sGoods = new sGoods;
                        $ress = $sGoods->save(array('status'=>5),array('sales_slip_id'=>$ids));
                        if (!$ress) {
                            throw new Exception('数据异常');
                        }
                    }

                    Db::name('examine_log')->insert(array(
                        'admin_id'=>session('admin')['id'],
                        'type'=>$type,
                        'createtime'=>time(),
                        'controller'=>'sales/slip',
                        'source_id'=>$ids,
                        'source'=>6,
                        'remark'=>'销售单',
                        'number'=>isset($row['number'])?$row['number']:'',
                    ));

                    if($status  == 2){
                        //添加记录
                        $sales_log_id = Db::name('customer_sales_log')->insertGetId(array(
                            'customer_id'=>$row['customer_id'],
                            'type'=>'销售单',
                            'type_id'=>1,
                            'number'=>$row['number'],
                            'source_id'=>$row['id'],
                            'createtime'=>time(),
                            'admin_id'=>$row['admin_id'],
                            'group_id'=>$row['group_id'],
                            'company'=>$row['company'],
                            'operator'=>$row['operator'],
                            'sales_num'=>$row['sales_num'],
                            'actual_cost'=>$row['actual_cost'],
                            'storehouse_id'=>$row['storehouse_id'],
                        ));
                        if(empty($sales_log_id)){
                            throw new Exception('数据异常');
                        }

                        $glists = Db::name('sales_goods')->where(array('sales_slip_id'=>$ids))->select();
                        foreach ($glists as $v){
                            Db::name('goods_sales_log')->insert(array(
                                'goods_id'=>$v['goods_id'],
                                'type'=>'销售单',
                                'type_id'=>1,
                                'number'=>$row['number'],
                                'source_id'=>$row['id'],
                                'createtime'=>time(),
                                'admin_id'=>$row['admin_id'],
                                'group_id'=>$row['group_id'],
                                'company'=>$row['company'],
                                'operator'=>$row['operator'],
                                'storehouse_id'=>$row['storehouse_id'],
                                'sales_log_id'=>$sales_log_id,
                            ));
                        }
                    }
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '成功'
                    );
                }
                throw new Exception('错误异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }


        $rows = Db::name('sales_goods')
            ->field('sg.sales_slip_id as slip_id, goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,storehouse_id,sg.status,sfhj')
            ->alias('sg')
            ->where(array('sales_slip_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        if(session('admin')['storehouse_id'] >0){
            $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
        }else{
            $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
        }

        $numbers = [];
        foreach ($rows as $k=>$v){
            $CheckoutGoods = new CheckoutGoods;
            $rows[$k]['sale_num'] = $CheckoutGoods->where(array('sales_slip_id'=>$v['slip_id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');

            $GoodsHouseStock = new GoodsHouseStock;
            $rows[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $rows[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $rows[$k]['buy_price'] = round($v['goods_num']*$v['sale_price'],2);
            $rows[$k]['tax_all'] = round($v['sale_price']*$v['tax']*$v['goods_num']/100,2);
            if($rows[$k]['sfhj'] == 0.00){
                $rows[$k]['sfhj'] = round(($v['sale_price']*$v['goods_num']*(1+$v['tax']/100)),2);
            }
            $numbers[] = $v['number'];
//            $rows[$k]['count'] = round(($v['sale_price']*$v['goods_num']*(1+$v['tax']/100)),2);
        }

        $url =  config('site.syncurl').'/api/sync/batchprice';

        $json = curl_post($url,array(
            'numbers'=>implode(',',$numbers),
            'code'=>$hrow['code'],
            'appkey'=>config('site.appkey'),
        ));
        $json = json_decode($json,true);
        if($json['code'] == 1){
            foreach ($rows as &$v){
                foreach ($json['data'] as $val){
                    if($v['number'] == $val['spec_num']){
                        $v['jxs_price'] = $val['jxs_price'];
                    }
                }
                if(!isset($v['jxs_price'])){
                    $v['jxs_price'] = 0;
                }
            }
        }else{
            foreach ($rows as &$v){
                $v['jxs_price'] = 0;
            }
        }

        $this->assign('row',$row);
        $this->assign('rows',$rows);

        return $this->view->fetch();
    }
    public function stop($ids=null){
        $sGoods = new sGoods;
        $row = $sGoods->where(array('id'=>$ids))->find();
        if(!$row){
            $this->error('商品信息不存在');
        }
        if($row['status']>2){
            $this->error('当前状态不允许中止');
        }
        //中止状态 如果都中止了 订单跟着中止
        Db::startTrans();
        try {
            $sGoods = new sGoods;
            $res = $sGoods->save(array('status' => 5), array('id' => $ids));
            if (!$res) {
                throw new Exception('状态异常');
            }
            $srow = $this->model->where(array('id'=>$row['sales_slip_id']))->find();
            if(!$srow){
                throw new Exception('数据异常');
            }
            //中止的数量
            $sGoods = new sGoods;
            $stopnum =  $sGoods->where(array('sales_slip_id'=>$row['sales_slip_id'],'status'=>5))->count();
            //总数量
            $sGoods = new sGoods;
            $num =  $sGoods->where(array('sales_slip_id'=>$row['sales_slip_id']))->count();
            if($num == $stopnum){
                $this->model->save(array('status'=>6),array('id'=>$row['sales_slip_id']));
            }
            Db::commit();
            return array(
              'code'=>1,
              'msg'=>'中止成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    public function edit($ids = null){

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        $row = $this->model->find($ids);
        if($row['status'] == 1 || $row['status'] == 7){

        }else{
            $this->error('状态不允许修改');
        }
        if ($this->request->isAjax()) {

            $customer_id = input('customer_id/d',0);
            $storehouse_id = input('storehouse_id/d',0);
            $deliverytime = strtotime(input('deliverytime'));
            $createtime = strtotime(input('createtime'));
            $tax = floatval(input('tax'));
            if(!is_float($tax) || $tax >17){
                $this->error('请检查税费');
            }
            $explain = input('explain','');
            $abstract = input('abstract','');
            $mobile = input('mobile','');
            $address = input('address','');
            $contacts = input('contacts','');
            $sales_type_id = input('sales_type_id',0);
            $sales_number = input('sales_number',0);

            $allfare = input('allfare/d',0);
            $discount = input('discount',0);
            $discount_explain = input('discount_explain','');
            $actual_cost = input('actual_cost',0);
            if(empty($actual_cost)){
                $this->success('总金额为空');
            }
            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            $sdata = $params['row'];
//            $sgids = [];
            $sale_num=0;
            $allprice = 0;
            foreach ($sdata as $k=> $v){
                $sdata[$k]['tax'] = floatval($v['tax']);
                if(!is_float($sdata[$k]['tax'])){
                    $this->error('商品'.$v['goods_id'].'税费设置有误');
                }
                $sale_num +=$v['goods_num'];
                $allprice+=$v['sfhj'];
//                $sgids[] = $v['goods_id'];
            }
//            if($allprice+$allfare !=$actual_cost){
            if(!compare($allprice+$allfare,$actual_cost)){
                $this->error('请检查总费用');
            }

//            $sGoods = new sGoods;
//            $idss = $sGoods->where(array('sales_slip_id'=>$ids))->select();
//            $actual_cost = 0;
            $saledata = array(
//                'createtime'=>$createtime,
                'sales_type_id'=>$sales_type_id,
                'sales_number'=>$sales_number,
                'allfare'=>$allfare,
                'discount'=>$discount,
                'discount_explain'=>$discount_explain,
                'actual_cost'=>$actual_cost,
                'deliverytime'=>$deliverytime,
                'customer_id'=>$customer_id,
                'storehouse_id'=>$storehouse_id,
                'explain'=>$explain,
                'abstract'=>$abstract,
                'address'=>$address,
                'mobile'=>$mobile,
                'contacts'=>$contacts,
                'tax'=>$tax,
                'sales_num'=>$sale_num,
            );
            Db::startTrans();
            try {
                $this->model->save($saledata,array('id'=>$ids));

                $gdata = [];
                $sGoods = new sGoods;
                $dres = $sGoods->where(array('sales_slip_id'=>$ids))->delete();

                if(!$dres){
                    throw new Exception('异常');
                }
                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'sfhj' => $v['sfhj'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'sales_slip_id' => $ids,
                        'customer_id'=>$customer_id,
                        'createtime'=>time(),
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'storehouse_id'=>$storehouse_id,
                    );
                }
                $sGoods = new sGoods;
                $sGoods->saveAll($gdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'编辑成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }


            exit;
        }

        $glist = Db::name('sales_goods')
            ->field('g.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,storehouse_id,sfhj')
            ->alias('sg')
            ->where(array('sales_slip_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        foreach ($glist as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $glist[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],$v['storehouse_id']);
            $glist[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],$v['storehouse_id']);
        }


        $Customer = new Customer;
        $crow = $Customer->find($row['customer_id']);
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('glist',$glist);
        $this->assign('row',$row);
        $this->assign('crow',$crow);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function examine($ids = null){
        $status = input('status/d',0);
        if(!$status){
            $this->error('非法操作');
        }
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        Db::startTrans();
        try {
            $res = $this->model->save(array('status' => $status), array('id' => $ids));
            if ($res) {
                if($status == 6){ //审核拒绝
                    $sGoods = new sGoods;
                    $ress = $sGoods->save(array('status'=>5),array('sales_slip_id'=>$ids));
                    if (!$ress) {
                        throw new Exception('数据异常');
                    }
                }
                Db::commit();
                return array(
                    'code' => 1,
                    'msg' => '成功'
                );
            }
            throw new Exception('错误异常');
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function gather(){
        return $this->view->fetch();
    }
    //商品汇总统计
    public function countget(){
        $start_time = !empty(input('start_time')) ? strtotime(input('start_time')):0;
        $end_time =  !empty(input('end_time')) ?strtotime(input('end_time')):time();
        $customer_id = input('customer_id/d',0);
        if(!empty($customer_id)){
            $crow = Db::name('customer')->where(array('id' => $customer_id))->find();
            $where['customer_id'] = isset($crow['id'])?$crow['id']:0;
        }
        $number = input('number');
        if(!empty($number)){
            $grow = Db::name('goods')->where(array('number' =>$number))->find();
            $where['goods_id']=isset($grow['id'])?$grow['id']:0;
        }
        $storehouse_id = input('storehouse_id/d',0);
        if(!empty($number)) {
            $where['storehouse_id']=$storehouse_id;
        }

        $where['sg.createtime'] = array('between time', [$start_time, $end_time]);
        $goods_num = Db::name('sales_goods')
            ->alias('sg')
            ->where($where)
            ->sum('goods_num');
        $price = Db::name('sales_goods')
            ->alias('sg')
            ->where($where)
            ->sum('goods_num*sale_price');
        $sfhj = Db::name('sales_goods')
            ->alias('sg')
            ->where($where)
            ->sum('sfhj');
        return array(
            'goods_num'=>$goods_num,
            'price'=>$price,
            'sfhj'=>$sfhj,
        );
    }
    public function gatherres(){
        $params = input();
        $start_time = input('starttime');
        $end_time = input('endtime');
        $number = input('number');

        if ($this->request->isAjax()) {
            $start_time = 0;
            $end_time = time();
            $filter = json_decode(input('filter'),true);
            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'customer_id' && !empty($v)){
//                        $crow = Db::name('customer')->where(array('id' => $v))->find();
                        $where['sg.customer_id'] = array('in',$v);
                    }
                    if($k == 'number' && !empty($v)){
//                        $grow = Db::name('goods')->where(array('id' =>array('in',explode(',',$v))))->column('id');
                        $where['goods_id']=array('in',explode(',',$v));
                    }
                    if($k == 'storehouse_id' && !empty($v)){
                        $where['sg.storehouse_id']=$v;
                    }
                    if($k == 'start_time' && !empty($v)){
                        $start_time = strtotime($v);
                    }
                    if($k == 'end_time' && !empty($v)){
                        $end_time = strtotime($v);
                    }
                }
            }

            $where['sg.createtime'] = array('between time', [$start_time, $end_time]);
            $where['sg.status'] = array('neq',5);
            $page = input('offset/d',0);
            $pagesize = input('limit/d',0);

            $list = Db::name('sales_goods')
                ->field('sg.id,sg.sales_slip_id,sg.sale_price,sg.operator,sg.ht_price,sg.goods_num,sfhj,g.title,g.specs,g.number gnumber,s.number,s.createtime,c.company,b.name,sg.remark')
                ->alias('sg')
                ->where($where)
                ->join('sales_slip s','sg.sales_slip_id = s.id')
                ->join('customer c','sg.customer_id =  c.id')
                ->join('goods g','sg.goods_id = g.id')
                ->join('supplier_brands b','g.brands_id = b.id','left')
                ->limit($page, $pagesize)
                ->order('s.id','DESC')
                ->select();
            foreach ($list as &$v){
                $v['goods_price'] = bcmul($v['sale_price'],$v['goods_num'],2);
                if($v['sfhj'] ==0.00){
                    $v['sfhj'] = bcmul($v['ht_price'],$v['goods_num'],2);
                }
            }
            $total =  Db::name('sales_goods')
                ->alias('sg')
                ->where($where)
                ->join('sales_slip s','sg.sales_slip_id = s.id')
                ->join('customer c','sg.customer_id =  c.id')
                ->join('goods g','sg.goods_id = g.id')
                ->join('supplier_brands b','g.brands_id = b.id','left')
                ->count();
            return  array(
                'rows'=>$list,
                'total'=>$total,
            );
        }

        if (isset($params['customer_id']) && !empty($params['customer_id'])) {
            $crow = Db::name('customer')->where(array('nickname' => $params['customer_id']))->find();
            if ($crow) {
                $customer_id = $crow['id'];
            }else{
                $customer_id = 0;
            }
        }else{
            $customer_id = 0;
        }

        $storehouse_id = input('storehouse_id/d',0);
        $this->assign('customer_id',$customer_id);
        $this->assign('storehouse_id',$storehouse_id);
        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('number',$number);
        return $this->view->fetch();
    }
    public function gatherres1(){
        $params = input();
        $start_time = input('starttime');
        $end_time = input('endtime');
        $number = input('number');

        if ($this->request->isAjax()) {
            $start_time = 0;
            $end_time = time();
            $filter = json_decode(input('filter'),true);
            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'customer_id' && !empty($v)){
                        $crow = Db::name('customer')->where(array('id' => $v))->find();
                        $where['customer_id'] = isset($crow['id'])?$crow['id']:0;
                    }
                    if($k == 'number' && !empty($v)){
                        $grow = Db::name('goods')->where(array('number' =>$v))->find();
                        $where['goods_id']=isset($grow['id'])?$grow['id']:0;
                    }
                    if($k == 'storehouse_id' && !empty($v)){
                        $where['s.storehouse_id']=$v;
                    }
                    if($k == 'start_time' && !empty($v)){
                        $start_time = strtotime($v);
                    }
                    if($k == 'end_time' && !empty($v)){
                        $end_time = strtotime($v);
                    }
                }
            }

            $where['zax_customer_sales_log.createtime'] = array('between time', [$start_time, $end_time]);

            $page = input('offset/d',0);
            $pagesize = input('limit/d',0);
            $list  = Db::name('customer_sales_log')
                ->where($where)
                ->field('s.*,c.company,h.name,gs.title,gs.specs')
                ->alias('s')
                ->join('goods_sales_log g','s.id = g.sales_log_id')
                ->join('goods gs','g.goods_id = gs.id')
                ->join('customer c','s.customer_id =  c.id')
                ->join('storehouse h','s.storehouse_id =  h.id')
                ->limit($page, $pagesize)
                ->order('s.id','DESC')
                ->select();

            $total  = Db::name('customer_sales_log')
                ->where($where)
                ->alias('s')
                ->join('goods_sales_log g','s.id = g.sales_log_id')
                ->join('customer c','s.customer_id = c.id')
                ->join('goods gs','g.goods_id = gs.id')
                ->join('storehouse h','s.storehouse_id =  h.id')
                ->count();;

            $sale_status = $this->model->slip_status();
            $factory =  new Sales();
            $factory_status = $factory->slip_status();
            foreach ($list as &$v){
                if($v['type_id'] == 1){//销售单
                    $table = 'sales_slip';
                    $status = $sale_status;
                    $trow = Db::name($table)->where(array('id'=>$v['source_id']))->find();
                    $v['explain'] =  $trow['explain'];
//                    $v['ht_price'] =  $trow['ht_price'];
                    $v['controller'] =  'sales/slip/detail';
                    $v['status'] =  $status[$trow['status']];
                    $v['deliver_num'] = Db::name('sales_checkout_goods')->where(array('sales_slip_id'=>$v['source_id']))->sum('goods_num');
                    $v['deliver_price'] = Db::name('sales_checkout_goods')->where(array('sales_slip_id'=>$v['source_id']))->sum('goods_num*sale_price');
                }
                if($v['type_id'] == 2){//直发单
                    $table = 'factory_sales';
//                    $model = 'factory_sales_goods';
                    $status = $factory_status;
                    $trow = Db::name($table)->where(array('id'=>$v['source_id']))->find();
                    if($trow['status'] >3 && $trow['status'] <6){
                        $v['deliver_num'] = $v['sales_num'];
                        $v['deliver_price'] = $v['actual_cost'];
                    }
                    $v['controller'] =  'factory/sales/detail';
                    $v['explain'] =  $trow['explain'];
                    $v['status'] =  $status[$trow['status']];
//                    $v['ht_price'] =  $trow['ht_price'];

                }

            }
            return  array(
              'rows'=>$list,
              'total'=>$total,
            );
        }

        if (isset($params['customer_id']) && !empty($params['customer_id'])) {
            $crow = Db::name('customer')->where(array('nickname' => $params['customer_id']))->find();
            if ($crow) {
                $customer_id = $crow['id'];
            }else{
                $customer_id = 0;
            }
        }else{
            $customer_id = 0;
        }
        $storehouse_id = input('storehouse_id/d',0);
        $this->assign('customer_id',$customer_id);
        $this->assign('storehouse_id',$storehouse_id);
        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('number',$number);
        return $this->view->fetch();
    }

    public function rational($ids = null){
        $row = $this->model->find($ids);
        if(empty($row) || $row['status'] != 7){
            $this->error('非法操作');
        }
        $numbers =[];
        $goodss = Db::name('sales_goods')
            ->alias('s')
            ->field('g.id,g.number,sale_price')
            ->where(array('sales_slip_id'=>$row['id']))
            ->join('goods g','s.goods_id = g.id')
            ->select();
        foreach ($goodss  as $k => $v){
            $numbers[] = $v['number'];
        }

        $hrow = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();
        $prices = $this->getprice(implode(',',$numbers),$hrow['code']);
        foreach ($prices as $v){
            foreach ($goodss as &$val){
                if($val['number'] == $v['spec_num']){
                    $val['jxs_price'] = $v['jxs_price'];
                }
            }
        }

        $slipstatus = 2;
        foreach ($goodss as $v){
            if(isset($v['jxs_price'])){ //
                if($v['jxs_price'] > $v['sale_price']){
                    $slipstatus = 1;
                }
            }else{
                $house = new Goods();
                $price = $house->getcost($v['id'],$row['storehouse_id']);
                if($price > $v['sale_price']){
                    $slipstatus = 1;
                }
            }
        }
        $this->success('检测成功','',$slipstatus);
    }

    //草稿转正式单子
    public function formal($ids = null){
        $row = $this->model->find($ids);
        if(empty($row) || $row['status'] != 7){
            $this->error('非法操作');
        }
        $numbers =[];
        $goodss = Db::name('sales_goods')
            ->alias('s')
            ->field('g.id,g.number,sale_price')
            ->where(array('sales_slip_id'=>$row['id']))
            ->join('goods g','s.goods_id = g.id')
            ->select();
        foreach ($goodss  as $k => $v){
            $numbers[] = $v['number'];
        }

        $hrow = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();
        $prices = $this->getprice(implode(',',$numbers),$hrow['code']);
        foreach ($prices as $v){
            foreach ($goodss as &$val){
                if($val['number'] == $v['spec_num']){
                    $val['jxs_price'] = $v['jxs_price'];
                }
            }
        }

        $slipstatus = 2;
        foreach ($goodss as $v){
            if(isset($v['jxs_price'])){ //
                if($v['jxs_price'] > $v['sale_price']){
                    $slipstatus = 1;
                }
            }else{
                $house = new Goods();
                $price = $house->getcost($v['id'],$row['storehouse_id']);
                if($price > $v['sale_price']){
                    $slipstatus = 1;
                }
            }
        }
        if($slipstatus == 2){
            $sales_log_id = Db::name('customer_sales_log')->insertGetId(array(
                'customer_id'=>$row['customer_id'],
                'type'=>'销售单',
                'type_id'=>1,
                'number'=>$row['number'],
                'source_id'=>$row['id'],
                'createtime'=>time(),
                'admin_id'=>$row['admin_id'],
                'group_id'=>$row['group_id'],
                'company'=>$row['company'],
                'operator'=>$row['operator'],
                'sales_num'=>$row['sales_num'],
                'actual_cost'=>$row['actual_cost'],
                'storehouse_id'=>$row['storehouse_id'],
            ));
            if(empty($sales_log_id)){
                $this->error('异常');
            }
            $glists = Db::name('sales_goods')->where(array('sales_slip_id'=>$ids))->select();
            foreach ($glists as $v){
                Db::name('goods_sales_log')->insert(array(
                    'goods_id'=>$v['goods_id'],
                    'type'=>'销售单',
                    'type_id'=>1,
                    'number'=>$row['number'],
                    'source_id'=>$row['id'],
                    'createtime'=>time(),
                    'admin_id'=>$row['admin_id'],
                    'group_id'=>$row['group_id'],
                    'company'=>$row['company'],
                    'operator'=>$row['operator'],
                    'storehouse_id'=>$row['storehouse_id'],
                    'sales_log_id'=>$sales_log_id,
                ));
            }
        }

        $res = $this->model->save(array('status'=>$slipstatus),array('id'=>$ids));
        if($res){
           $this->success('转换成功');
        }else{
            $this->error('转换失败');
        }
    }

    //废弃记录
    public function feiqi(){
        $params = input();
        $start_time = strtotime(input('starttime'));
        $end_time = strtotime(input('endtime'));

        $where1 = '';
        if (isset($params['customer_id'])) {
            $crow = Db::name('customer')->where(array('nickname' => $params['customer_id']))->find();
            if ($crow) {
                $where['customer_id'] = $crow['id'];
                $where1 .= 'customer_id = ' . $crow['id'] . '';
            }
        }
        $where['createtime'] = array('between time', [$start_time, $end_time]);
        $where1 .= ' AND createtime BETWEEN ' . $start_time . ' AND ' . $end_time . '';
        //explain 字段不能用
        $field = 'number,company,createtime,operator,`explain`,actual_cost';

//        dump('SELECT '.$field.' FROM zax_sales_slip where '.$where1.'');
        $page = input('offset/d',0);
        $pagesize = input('limit/d',0);
        $list = Db::field($field)
            ->table('zax_factory_sales')
//            ->union('SELECT name FROM zax_factory_sales',true)
            ->union('SELECT ' . $field . ' FROM zax_sales_slip where ' . $where1 . '', true)
            ->limit($page, $pagesize)
            ->where($where)
            ->order('createtime', 'ASC')
            ->select();
        $total1 = Db::field($field)
            ->table('zax_factory_sales')
//            ->union('SELECT name FROM zax_factory_sales',true)
            ->where($where)
            ->count();
        $total2 = Db::name('sales_slip')->where($where)->count();
        return  array(
            'rows'=>$list,
            'total'=>$total2+$total1,
        );
    }
    //单据转换
    public function change($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        if($row['status'] != 2){
            $this->error('订单状态异常');
        }
        $hnuo = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();
        if(!$hnuo){
            $this->error('数据异常');
        }
        if($this->request->isAjax()) {
            $state = input('state/d',0);
            $idss = input('idss/a');
            if($state == 2){ //整单转换
                $rows = Db::name('sales_goods')
                    ->field('sg.sales_slip_id as slip_id, goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,storehouse_id,sg.status,sfhj')
                    ->alias('sg')
                    ->where(array('sales_slip_id' => $ids))
                    ->join('goods g', 'sg.goods_id = g.id')
                    ->select();
                $allfare = 0;
                foreach ($rows as $v) {
                    if ($v['goods_id'] == 1) {
                        $allfare = $v['ht_price'];
                    }
                }
                $num = Db::name('factory_sales')->where(array('createtime' => array('>', strtotime(date('Y-m-d', time())))))->count();
//                $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
                $data = array(
                    'number' => 'ZF-T-' . date('Y-m-d') . '-' . getnumber($num),
                    'createtime' => time(),
                    'admin_id' => $row['admin_id'],
                    'group_id' => $row['group_id'],
                    'company' => $row['company'],
                    'operator' => $row['operator'],
                    'customer_id' => $row['customer_id'],
                    'explain' => $row['explain'],
                    'tax' => $row['tax'],
                    'contacts' => $row['contacts'],
                    'address' => $row['address'],
                    'mobile' => $row['mobile'],
                    'actual_cost' => $row['actual_cost'],
                    'sales_num' => $row['sales_num'],
                    'allfare' => $row['allfare'] + $allfare,
                    'storehouse_id' => $row['storehouse_id'],
                    'sales_slip_id' => $row['id'],
                );
                Db::startTrans();
                try {
                    $sales_id = Db::name('factory_sales')->insertGetId($data);
                    if (empty($sales_id)) {
                        throw new Exception('数据异常2');
                    }
                    $gdata = [];
                    foreach ($rows as $v) {
                        if ($v['goods_id'] == 1) {
                            continue;
                        }
                        $this->syncstock($v['goods_id'],$v['number'],$row['storehouse_id'],$hnuo['code']);
                        $gdata[] = array(
                            'goods_id' => $v['goods_id'],
                            'goods_num' => $v['goods_num'],
                            'sale_price' => $v['sale_price'],
                            'ht_price' => $v['ht_price'],
                            'sfhj' => $v['sfhj'],
                            'tax' => $v['tax'],
                            'remark' => $v['remark'],
                            'customer_id' => $row['customer_id'],
                            'factory_sales_id' => $sales_id,
                            'createtime' => time(),
                            'admin_id' => $row['admin_id'],
                            'group_id' => $row['group_id'],
                            'company' => $row['company'],
                            'operator' => $row['operator'],
                            'storehouse_id' => $row['storehouse_id'],
                            'sales_slip_id' => $row['id'],
                        );
                    }
                    $sGoods = new fGoods;
                    $sGoods->saveAll($gdata);

                    $res = $this->model->save(array('status' => 8), array('id' => $ids));
                    if (empty($res)) {
                        throw new Exception('数据异常');
                    }
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '转换成功',
                    );
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }else{
                if(empty($idss)){
                    $this->error('没有选择商品');
                }
                foreach ($idss as $val){
                    if($val['num'] <1){
                        $this->error('非法操作,如有异常,联系管理员');
                    }
                }
                $gids = [];
                foreach ($idss as $v){
                    $gids[] = $v['id'];
                }

                $rows = Db::name('sales_goods')
                    ->field('sg.id,sg.sales_slip_id as slip_id, goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,storehouse_id,sg.status,sfhj')
                    ->alias('sg')
                    ->where(array('sales_slip_id' => $ids,'sg.id'=>array('in',$gids)))
                    ->join('goods g', 'sg.goods_id = g.id')
                    ->select();
                foreach ($rows as $k=> $v){
                    foreach ($idss as $val){
                        if($v['id'] == $val['id']){
                            $rows[$k]['change_num'] = $val['num'];
                        }
                    }
                }


                $actual_cost = 0;
                $sales_num = 0;
                foreach ($rows as $v){
                    if($v['change_num'] == $v['goods_num']){
                        $actual_cost+=$v['sfhj'];
                        $sales_num+=$v['goods_num'];
                    }else{
                        $actual_cost+=$v['ht_price']*$v['change_num'];
                        $sales_num+=$v['change_num'];
                    }

                }

                $num = Db::name('factory_sales')->where(array('createtime' => array('>', strtotime(date('Y-m-d', time())))))->count();
                $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
                $data = array(
                    'number' => 'ZF-T-' . date('Y-m-d') . '-' . getnumber($num),
                    'createtime' => time(),
                    'admin_id' => $row['admin_id'],
                    'group_id' => $row['group_id'],
                    'company' => $row['company'],
                    'operator' => $row['operator'],
                    'customer_id' => $row['customer_id'],
                    'explain' => $row['explain'],
                    'tax' => $row['tax'],
                    'contacts' => $row['contacts'],
                    'address' => $row['address'],
                    'mobile' => $row['mobile'],
                    'actual_cost' => $actual_cost,
                    'sales_num' => $sales_num,
                    'allfare' => 0,
                    'storehouse_id' => $row['storehouse_id'],
                    'sales_slip_id' => $row['id'],
                );
                Db::startTrans();
                try {
                    $sales_id = Db::name('factory_sales')->insertGetId($data);
                    if (empty($sales_id)) {
                        throw new Exception('数据异常3');
                    }
                    $gdata = [];
                    foreach ($rows as $v) {
                        if ($v['goods_id'] == 1) {
                            continue;
                        }
                        $this->syncstock($v['goods_id'],$v['number'],$row['storehouse_id'],$hnuo['code']);
                        $tsfhj = $v['sfhj'];
                        if($v['change_num'] !=$v['goods_num']){
                            $tsfhj = $v['ht_price']*$v['change_num'];
                        }
                        $gdata[] = array(
                            'goods_id' => $v['goods_id'],
                            'goods_num' => $v['change_num'],
                            'sale_price' => $v['sale_price'],
                            'ht_price' => $v['ht_price'],
                            'sfhj' => $tsfhj,
                            'tax' => $v['tax'],
                            'remark' => $v['remark'],
                            'customer_id' => $row['customer_id'],
                            'factory_sales_id' => $sales_id,
                            'createtime' => time(),
                            'admin_id' => $row['admin_id'],
                            'group_id' => $row['group_id'],
                            'company' => $row['company'],
                            'operator' => $row['operator'],
                            'storehouse_id' => $row['storehouse_id'],
                            'sales_slip_id' => $row['id'],

                        );

                        if($v['change_num'] == $v['goods_num']){//所有数量转换
                            $res =  Db::name('sales_goods')->where(array('id'=>$v['id']))->update(array('status'=>6));
                            if (empty($res)) {
                                throw new Exception('数据异常5');
                            }
                        }else{
                            $already_num = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$row['id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');
                            if($already_num + $v['change_num'] == $v['goods_num']){//所有数量被转换
                                $res =  Db::name('sales_goods')->where(array('id'=>$v['id']))->update(array('status'=>6));
                                if (empty($res)) {
                                    throw new Exception('数据异常6');
                                }
                            }
                            if($already_num + $v['change_num'] > $v['goods_num']) {//所有数量被转换
                                throw new Exception('数据超出原定销售数量');
                            }
                        }
                    }
                    $sGoods = new fGoods;
                    $sGoods->saveAll($gdata);

                    $nochangecount = Db::name('sales_goods')->where(array('sales_slip_id'=>$ids,'status'=>array('neq',6)))->count();
                    if($nochangecount == 0){
                        Db::name('sales_slip')->where(array('id'=>$ids))->update(array('status'=>8));
                    }

                    $EnterGoods = new CheckoutGoods;
                    $egoodcont = $EnterGoods->where(array('sales_slip_id' => $ids, 'status'=>array('>',0)))->sum('goods_num');
                    $change_num = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$ids,'status'=>array('>',0)))->sum('goods_num');
                    if($egoodcont >0 && $egoodcont + $change_num == $row['sales_num']){
                        Db::name('sales_slip')->where(array('id'=>$ids))->update(array('status'=>4));
                    }



                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '转换成功',
                    );
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                exit;
            }
            exit;

        }
        $rows = Db::name('sales_goods')
            ->field('sg.sales_slip_id as slip_id, goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,storehouse_id,sg.status,sfhj')
            ->alias('sg')
            ->where(array('sales_slip_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        foreach ($rows as $k=>$v){
            //直发数量
            $cnum = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$v['slip_id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');
            //出库数量
            $CheckoutGoods = new CheckoutGoods;
            $checkout_goods = $CheckoutGoods->where(array('sales_slip_id'=>$v['slip_id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');
            $rows[$k]['sale_num'] = $checkout_goods;
            $rows[$k]['change_num'] = $v['goods_num']- $cnum;



            $GoodsHouseStock = new GoodsHouseStock;
            $rows[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $rows[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $rows[$k]['buy_price'] = round($v['goods_num']*$v['sale_price'],2);
            $rows[$k]['tax_all'] = round($v['sale_price']*$v['tax']*$v['goods_num']/100,2);
            if($rows[$k]['sfhj'] == 0.00){
                $rows[$k]['sfhj'] = round(($v['sale_price']*$v['goods_num']*(1+$v['tax']/100)),2);
            }

        }
        $this->assign('ids',$ids);
        $this->assign('row',$row);
        $this->assign('rows',$rows);
        return $this->view->fetch();
    }
    public function cancelbill($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if($row['status'] != 2){
            $this->error('状态异常');
        }
        $count = Db::name('sales_checkout')->where(array('sales_slip_id'=>$ids,'status'=>array('<',5)))->count();
        if(!empty($count)){
            $this->error('请先处理出库单');
        }
        $count = Db::name('factory_sales')->where(array('sales_slip_id'=>$ids,'status'=>array('<',6)))->count();
        if(!empty($count)){
            $this->error('请先处理直发单');
        }

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();


        Db::startTrans();
        try {
            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 6,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'sales/slip',
                    'source_id' => $row['id'],
                    'number' => isset($row['number']) ? $row['number'] : '',
                    'createtime' => time(),
                ));
            //审核记录
            Db::name('examine_log')->insert(array(
                'admin_id' => session('admin')['id'],
                'type' => 3,
                'createtime' => time(),
                'controller' => 'sales/slip',
                'source_id' => $ids,
                'source' => 6,
                'remark' => '销售单',
                'number' => isset($row['number']) ? $row['number'] : '',
            ));

            $sGoods = new sGoods;
            $sGoods->save(array('status' => 5), array('sales_slip_id' => $ids));

            $res = $this->model->save(array('status' => 9), array('id' => $ids));
            if ($res) {
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'中止成功',
                );
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    //回退订单状态
    public function history($ids = null){
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('异常');
        }
        if($row['status'] !=2){
            $this->error('状态异常');
        }
        $frow = Db::name('factory_sales')->where(array('sales_slip_id'=>$ids,'status'=>array('<',6)))->find();
        if($frow){
            $this->error('该订单有分支直发，不允许回退');
        }
        $res = $this->model->save(array('status'=>1),array('id'=>$ids));
        if(empty($res)){
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
    public function del($ids=null){
        Db::startTrans();
        try {
            $row = $this->model->find($ids);
            if($row['status'] != 7){
                throw new Exception('状态异常');
            }

            $sGoods = new sGoods;
            $sGoods->where(array('sales_slip_id'=>$ids))->delete();
            $this->model->where(array('id'=>$ids))->delete();
            Db::commit();
            return array(
                'code' => 1,
                'msg' => '删除成功',
            );
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    //同步库存  设置是否需要及时同步
    protected function syncstock($goods_id,$number,$storehouse_id,$code){
        $GoodsHouseStock = new GoodsHouseStock;
        $stock = $GoodsHouseStock->getstock($goods_id,$storehouse_id);
        if($stock>0){
            $url = config('site.syncurl').'/api/sync/syncstock';
            curl_post($url,array(
                'spec_num'=>$number,
                'code'=>$code,
                'stock'=>$stock,
                'appkey'=>config('site.appkey'),
            ));
        }
    }
}
